import axios from 'axios'

const chatService = {
  async sendMessage(message, fileIds, onChunk) {
    try {
      const formData = new FormData()
      formData.append('userInput', message)
      if (fileIds && fileIds.length > 0) {
        formData.append('fileIds', JSON.stringify(fileIds))
      }
      const response = await fetch('/api/chat/assistant', {
        method: 'POST',
        body: formData
      })
      
      if (!response.ok) {
        let errorMsg = '发送消息失败';
        try {
          const data = await response.json();
          if (data && data.error) {
            errorMsg = data.error;
          }
        } catch {}
        throw new Error(errorMsg);
      }
      
      const reader = response.body.getReader()
      const decoder = new TextDecoder('utf-8')
      let buffer = ''
      
      while (true) {
        const { done, value } = await reader.read()
        
        if (done) {
          break
        }
        
        const chunk = decoder.decode(value, { stream: true })
        const lines = (buffer + chunk).split('\n')
        
        buffer = lines.pop() || ''
        
        for (const line of lines) {
          if (line.trim() === '') continue
          
          if (line.startsWith('data:')) {
            try {
              const jsonData = JSON.parse(line.substring(5).trim())
              if (jsonData.content) {
                onChunk(jsonData.content)
              }
            } catch (e) {
              console.error('解析消息时出错:', e)
            }
          }
        }
      }
      
      return true
    } catch (error) {
      console.error('发送消息失败:', error)
      throw error
    }
  },
  async uploadFile(file) {
    const formData = new FormData()
    formData.append('file', file)
    const response = await fetch('/api/upload-file', {
      method: 'POST',
      body: formData
    })
    if (!response.ok) {
      throw new Error('文件上传失败')
    }
    const data = await response.json()
    return data // 期望返回 { id, name, size, ... }
  }
}

export { chatService } 